package com.vertx.starter;

import com.google.common.base.Stopwatch;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;

import java.util.concurrent.TimeUnit;

@Log4j2
public class AppVerticalDeployAgentImpl implements AppVerticalDeployAgent {
    private final Vertx vertx;

    public <T extends AppVerticle> Future<String> deployVerticle(Class<T> clazz) {
        AppVerticalMeta meta = (AppVerticalMeta) clazz.getAnnotation(AppVerticalMeta.class);
        String name = VertxUtils.getGuiceClassName(clazz);
        DeploymentOptions options = (new DeploymentOptions()).setWorker(meta != null && meta.type() == AppVerticalType.WORKER).setInstances(meta == null ? 1 : meta.instanceCount());
        return this.deployVerticle(name, options);
    }

    public <T extends AppVerticle> Future<String> deployVerticle(Class<T> clazz, DeploymentOptions options) {
        String name = VertxUtils.getGuiceClassName(clazz);
        return this.deployVerticle(name, ObjectUtils.defaultIfNull(options, new DeploymentOptions()));
    }

    private Future<String> deployVerticle(String name, DeploymentOptions options) {
        Stopwatch stopWatch = Stopwatch.createStarted();
        log.info("开始部署Vertical!名称: {} 选项: {}", name, options.toJson());
        return this.vertx.deployVerticle(name, options).onFailure((e) -> {
            log.error("失败部署Vertical!名称: {}", name, e);
        }).onComplete((__) -> {
            log.info("结束部署Vertical!名称: {} 耗时: {}ms", name, stopWatch.elapsed(TimeUnit.MILLISECONDS));
        });
    }

    public AppVerticalDeployAgentImpl(Vertx vertx) {
        this.vertx = vertx;
    }
}
